package com.wx.daoImpl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.wx.dao.UserDao;
import com.wx.model.Users;
import com.wx.util.DBUtil;

public class UserDaoImpl implements UserDao {

	@Override
	public boolean regist(Users user) throws Exception {
		Connection connection = DBUtil.getConnection();
		PreparedStatement ps = connection.prepareStatement("insert into users(username,password) values(?,?)");
		ps.setString(1, user.getUsername());
		ps.setString(2,user.getPassword());
		int i = ps.executeUpdate();
		boolean b=false;
		ps.close();
		connection.close();
		if(i>0){
			b=true;
		}
		return  b;
	}
	public void registAll(Users user) throws Exception{
		Connection connection = DBUtil.getConnection();
		PreparedStatement ps = connection.prepareStatement("update users set truename=?,gender=?,phone=?,home=?,postcode=? where username=?");
		ps.setString(1,user.getTruename());
		ps.setString(2,user.getGender());
		ps.setString(3,user.getPhone());
		ps.setString(4,user.getHome());
		ps.setInt(5,user.getPostcode());
		ps.setString(6,user.getUsername());
		ps.executeUpdate();
		ps.close();
		connection.close();
	}

	@Override
	public Users login(Users user) throws Exception {
		Connection connection = DBUtil.getConnection();
		PreparedStatement ps = connection.prepareStatement("select username,password from users where username=? and password=?");
		ps.setString(1, user.getUsername());
		ps.setString(2, user.getPassword());
		ResultSet rs = ps.executeQuery();
		Users users=new Users();
		if(rs.next()){
			users.setUserid(user.getUserid());
			users.setUsername(user.getUsername());
			users.setPassword(user.getPassword());
		}
		rs.close();
		ps.close();
		connection.close();
		return users;
	}
	
	@Override
	public boolean checkUsername(String username) throws Exception {
		boolean b=true;
		Connection connection = DBUtil.getConnection();
		PreparedStatement ps = connection.prepareStatement("select username from users where username=?");
		ps.setString(1, username);
		ResultSet rs = ps.executeQuery();
		if(rs!=null){
			b=false;
		}
		return b;
	}
}
